package erbedo.call.tracker;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	
    public static final String KEY_ROWID = "id";
    public static final String KEY_FILTER = "filter";
        
    private static final String TAG = "DBAdapter";
    
    private static final String DATABASE_NAME = "filters";
    private static final String DATABASE_TABLE = "list";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE =
        "create table if not exists list (id INTEGER PRIMARY KEY AUTOINCREMENT, "
        + "filter text);";
        
    private final Context context; 
    
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
    
    public boolean cleanDb() {
    	String delete = "DELETE FROM "+DATABASE_TABLE;
    	db.execSQL(delete);
    	return true;
    }
        
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion 
                    + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS titles");
            onCreate(db);
        }
    }    
    
    //---opens the database---
    public DBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() {
        DBHelper.close();
    }
    
    //---insert a title into the database---
    public long insertFilter(String filter) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_FILTER, filter);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---retrieves all the titles---
    public Cursor getAllFilters() {
        return db.query(DATABASE_TABLE, new String[] {KEY_FILTER}, 
                null, 
                null, 
                null, 
                null, 
                "id");
    }
    
    public boolean deleteFilter(String toDelete) {
    	String delete = "DELETE FROM "+ DATABASE_TABLE + " WHERE " + KEY_FILTER + " = '" + toDelete + "'" ;
    	db.execSQL(delete);
    	return true;
    }
}